package com.csgc.camera.biz.other

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.text.Editable
import androidx.activity.viewModels
import androidx.core.widget.addTextChangedListener

import com.csgc.camera.base.BaseBindingActivity
import com.csgc.camera.bean.BindPhoneParams
import com.csgc.camera.bean.SendCodeParams
import com.csgc.camera.bean.UserInfo

import com.csgc.camera.events.BindPhoneEvents
import com.csgc.camera.http.doFailure
import com.csgc.camera.http.doSuccess
import com.csgc.camera.http.viewmodel.AppViewModel
import com.csgc.camera.storage.UserPreference
import com.csgc.camera.util.AppUtil
import com.csgc.camera.util.clickWithTrigger
import com.cysd.spsyxj.R
import com.cysd.spsyxj.databinding.ActivityBindPhoneBinding

import com.drake.channel.sendEvent
import com.gyf.immersionbar.ktx.immersionBar
import com.hjq.toast.ToastUtils
import com.squareup.moshi.JsonAdapter
import com.squareup.moshi.Moshi

class BindPhoneActivity:BaseBindingActivity<ActivityBindPhoneBinding>(ActivityBindPhoneBinding::inflate) {

    companion object{
        fun launch(context: Context){
            context.startActivity(Intent(context,BindPhoneActivity::class.java))
        }
    }
    private val viewModel:AppViewModel by viewModels()
    private val userJsonAdapter: JsonAdapter<UserInfo> by lazy{
        val moshi = Moshi.Builder().build()
        val jsonAdapter =  moshi.adapter(UserInfo::class.java)
        jsonAdapter
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        immersionBar {
            fitsSystemWindows(true)
            //白色状态栏，黑色字体
            statusBarColor(R.color.white)
            statusBarDarkFont(true)

        }
        initListener()
        initData()

    }


    private fun initListener(){
        binding.ivBack.clickWithTrigger { finish() }
        binding.etPhoneNum.addTextChangedListener { text: Editable? ->
            text?.let {

                if (binding.cvLoginCountdown.currentSecond == 0){
                    binding.cvLoginCountdown.isEnabled = it.toString().isNotEmpty()
                }
            }
        }
        binding.cvLoginCountdown.clickWithTrigger {
            val phoneNum = binding.etPhoneNum.text.toString().trim()
            if (phoneNum.isEmpty()){
                ToastUtils.show("请输入手机号")
                return@clickWithTrigger
            }
            if (phoneNum.length != 11 || !phoneNum.startsWith("1")){
                ToastUtils.show("请输入正确手机号")
                return@clickWithTrigger
            }
            //调用接口获取验证码
            viewModel.sendSmsCode(SendCodeParams(phoneNum,packageName))



        }

        binding.tvBindPhone.clickWithTrigger {
            val phoneNum = binding.etPhoneNum.text.toString().trim()
            if (phoneNum.isEmpty()){
                ToastUtils.show("请输入手机号")
                return@clickWithTrigger
            }
            if (phoneNum.length != 11 || !phoneNum.startsWith("1")){
                ToastUtils.show("请输入正确手机号")
                return@clickWithTrigger
            }
            val code = binding.etCodeNumber.text.toString().trim()
            if (code.isEmpty()){
                ToastUtils.show("请输入验证码")
                return@clickWithTrigger
            }

            viewModel.bindPhone(BindPhoneParams(phoneNum,code,UserPreference.instance.getOaid(),UserPreference.instance.getUserToken(),packageName, AppUtil.getChannel()))


        }

    }

    private fun initData(){
        viewModel.bindPhoneResult.observe(this){result->
            result.doSuccess { baseResponse ->

                baseResponse.data?.let { info->
                    UserPreference.instance.setUserInfo(userJsonAdapter.toJson(info))
                    sendEvent(BindPhoneEvents(true))
                    finish()
                }


            }
            result.doFailure {
                ToastUtils.show("${it?.message}")
            }

        }

        viewModel.codeResult.observe(this){result->
            result.doSuccess {
                ToastUtils.show("验证码已发送")
                binding.cvLoginCountdown.start()
            }
            result.doFailure {
                ToastUtils.show("验证码发送失败${it?.message}")
            }

        }

    }


    override fun onDestroy() {
        super.onDestroy()
        binding.cvLoginCountdown.stop()
    }

}